const fs = require('fs')
const path = require('path')

const projectSrc = path.resolve(__dirname, './')
const resolve = route => path.resolve(projectSrc, route)



fs.readFile(resolve('./file.js'), 'utf-8', (err, data) => {
  if (err) {
    console.log(err)
    throw err
  }
  handlerSvgFile(data)
})


async function handlerSvgFile (data) {
  const symbols = [...data.toString().matchAll(/<symbol id="(.*?)".+?>(.*?)<\/symbol>/g)]
  const symbolLength = symbols.length

  console.log(symbols.length)
  console.log('--------')
  console.log(0, symbols[0][0])
  console.log(1, symbols[0][1])
  console.log(2, symbols[0][2])

  for (let i = 0; i < symbolLength; i++) {
    const currentSvg = symbols[i]
    //
    const id = currentSvg[1]
    const svgContent = currentSvg[2]


    const svg = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 1024 1024" version="1.1">${svgContent}</svg>`
    const fileName = `${id}.svg`


    await writEmionFile(fileName, svg)

  }

}


async function writEmionFile (fileName, svg) {


  const filePath = resolve(`files/${fileName}`)
  fs.writeFile(filePath, svg, err => {
    if (err) throw err;
    console.log(`The file(${fileName}) has been saved !`);
  })


}

